import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;

public class FileOperation {
    public static boolean readFile(String filename, List<String> words){
        if(null == filename || null == words){
            System.out.println("filename is null or words is null");
            return false;
        }
        Scanner scanner = null;
        try{
            File file = new File(filename);
            if(file.exists()){
                FileInputStream fileInputStream = new FileInputStream(file);
                scanner = new Scanner(new BufferedInputStream(fileInputStream),"UTF-8");
                scanner.useLocale(Locale.ENGLISH);
            }else{
                return false;
            }

            //简单分词
            if(scanner.hasNextLine()){
                String contents = scanner.useDelimiter("\\A").next();
                int start = firstCharactorIndex(contents,0);
                for(int i=start+1;i<=contents.length();){
                    if(i==contents.length() || !Character.isLetter(contents.charAt(i))){
                        String word = contents.substring(start, i).toUpperCase();
                        words.add(word);
                        start = firstCharactorIndex(contents,i);
                        i = start + 1;
                    }else{
                        i++;
                    }
                }
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    private static int firstCharactorIndex(String contents, int index) {
        for(int i=index;i<contents.length();i++){
            if(Character.isLetter(contents.charAt(i))){
                return i;
            }
        }
        return contents.length();
    }
}
